package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.SubjectAttribute;
import model.UserAccount;
import util.Log;
import validator.AttributeValidator;
import web.JSONMessage;
import db.ImbiConnection;

public class AttributeController extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {		
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");		
		if(u != null){		
			if(request.getParameter("delete")!= null){				
				deleteAttribute(request, response);
			} else insertAttribute(request, response);
		}
	}

	private void deleteAttribute(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		try{
			int id = Integer.parseInt(request.getParameter("id"));			
			ImbiConnection.getSubjectAttributeDAO().delete(new SubjectAttribute(id, 0,0,0,0,"",0,null,0));
			response.getWriter().write(JSONMessage.message("Attribute removed"));
			Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" deleted attribute "+id);
		} catch(NumberFormatException e){
			response.getWriter().write(JSONMessage.errorMessage("Illegal parameters"));
		}	
		
	}

	private void insertAttribute(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		AttributeValidator validator = new AttributeValidator(
			request.getParameter("attribute_subject"),
			request.getParameter("attribute_type"),
			request.getParameter("attribute_subject_type"),
			request.getParameter("attribute_order"),
			request.getParameter("attribute_value")
		);
		if(validator.isValid()){
			SubjectAttribute attribute = new SubjectAttribute(
				0, validator.getSubject(), 
				validator.getAttributeType(), 
				validator.getSubjectType(), 
				validator.getOrderby(), 
				validator.getStringValue(), 
				validator.getIntValue(), 
				validator.getDateValue(), 
				validator.getDataType()
			);
			ImbiConnection.getSubjectAttributeDAO().insert(attribute);
			Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" inserted attribute "
					+attribute.getSubjectAttributeType()+" for "+attribute.getSubjectTypeString()+" "+attribute.getSubject());
			response.getWriter().write(JSONMessage.message("Attribute added"));
		}		
		response.getWriter().write(JSONMessage.errorMessage("Invalid parameters"));
	}
}
